import router from './router'
import store from './store'
import { transform } from '@/utils/trans'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式
// import { Message } from 'element-ui'
import { getToken } from '@/utils/auth' // 验权
import Layout from '@/views/layout/Layout'
import { asyncRouterMap } from './router'
var getRouter = []
const a = []
const whiteList = ['/login'] // 不重定向白名单
router.beforeEach((to, from, next) => {
  // debugger
  NProgress.start()
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      if (getRouter.length === 0) {
        // debugger
        store.dispatch('getRoles').then(res => {
          console.log(res)
          console.log(asyncRouterMap)
          res.forEach(val => {
            asyncRouterMap.forEach(el => {
              if (val.name === el.title) {
                a.push(el)
              }
            })
          })
          getRouter = transform(a, 'id', 'parentId', 'children')
          console.log(a)
          store.dispatch('GenerateRoutes', getRouter).then(() => { // 生成可访问的路由表
            router.addRoutes(getRouter) // 动态添加可访问路由表
            localStorage.getRouter = JSON.stringify(getRouter)
            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
          })
        })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login') // 否则全部重定向到登录页
      // next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})
